package com.example.webcrawlercoursedesign;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

public class FragmentSina extends Fragment {
	private Context context;
	private List<News> newsList;//添加新闻
	private NewsAdapter adapter;//新闻适配器
	private Handler handler;
	private ListView listView;//展示新闻列表
	private NewsCache cache;//缓存管理


	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		//fragment的布局
		context = getActivity();
		View fragmentView = inflater.inflate(R.layout.fragment_sina, container, false);
		newsList = new ArrayList<>();//新闻列表
		listView = fragmentView.findViewById(android.R.id.list);
		cache = new NewsCache(context);
		getNews(context);//获取新闻
		/**
		 * 又开一个线程
		 *判断message
		 * 装上适配器
		 * 适配器版本的点击事件
		 */
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					adapter = new NewsAdapter(context, newsList);//适配器
					listView.setAdapter(adapter);//设置适配器
					listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//这一部分是点击之后转到新闻内容页面
							/**
							 * 获取位置,把数据装进news
							 * intent切换布局
							 * 传输数据
							 * 启动
							 */
							News news = newsList.get(position);//往定好数据框架的news里面传入数据
							Intent intent = new Intent(getActivity(), NewsDisplayActivity.class);//转到展示新闻的界面
							intent.putExtra("news_url", news.getNewsUrl());//把要打开的网址给他
							startActivity(intent);
						}
					});
				}
			}
		};
		return fragmentView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	private void getNews(final Context context) {

		new Thread(new Runnable() {
			@Override
			public void run() {
				if (!cache.isNetworkAvailable(context)){//无网络连接时加载库数据
					newsList = cache.loadCache(MySQLite.SINA_NAME);
				}
				else {
					String sinaAPI = "http://cre.dp.sina.cn/api/v3/get?cre=tianyi&mod={0}&merge=3&statics=1&length=10";
					String[] mods = {"wnews", "wmil", "wtech", "wfin", "wedu",
							"wspt", "went", "wgame", "wblog", "whealth"};
					//新闻军事科技财经教育体育娱乐游戏博客健康
					//手机新浪网json数据源
					try {
						for (int i = 0; i < mods.length; i++){
							String temp = Jsoup.connect(MessageFormat.format(sinaAPI, mods[i])).ignoreContentType(true).get().toString();
							String jsonString = TextUtils.substring(temp, temp.indexOf('{'), temp.lastIndexOf('>'));
							//获取json格式字符串
							Log.d("url", jsonString);
							JSONObject jsonObject = new JSONObject(jsonString);//转换为json数据
							JSONArray jA = jsonObject.getJSONArray("data");//取jsonArray
							for (int j = 0; j < jA.length(); j++){
								JSONObject jO = (JSONObject)jA.get(j);
								String title, url, desc, time, imageUrl;
								//手机新浪网json格式->内容（标签）：标题（title或mtitle）、url（url）、内容提要（intro或无）
								//来源（media或无）、题图（thumb或mthumb）
								if (jO.has("title") && jO.has("intro") && jO.has("thumb") &&
										jO.has("media")){
									title = jO.get("title").toString();
									desc = subLength(jO.get("intro").toString(), 40);
									imageUrl = jO.get("thumb").toString();
									time = jO.get("media").toString();
								}
								else{
									title = jO.get("mtitle").toString();
									desc = null;
									imageUrl = jO.getJSONArray("mthumbs").getString(0);
									time = null;
								}
								url = jO.get("url").toString();
								News news = new News(title, url, desc, time, imageUrl);
								newsList.add(news);
							}
						}
						cache.updateCache(newsList, MySQLite.SINA_NAME);//更新数据库
					}catch (Exception e){
						e.printStackTrace();
					}
				}
				Message msg = new Message();
				msg.what = 1;
				handler.sendMessage(msg);
			}
		}).start();
	}

	public String subLength(String str, int length){
		if (str.length() <= length){
			return str;
		}
		return str.substring(0, length) + "...";
	}
}
